import 'package:cave_flutter/model/dynamic_model.dart';
import 'package:cave_flutter/pages/whl_home/whl_publish/push_top_setting/push_top_setting_sheet.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/widgets/empty_widget.dart';
import 'package:cave_flutter/widgets/refresh_widget.dart';
import 'package:cave_flutter/widgets/whl_button.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../common/common_widget.dart';
import '../../model/base_model.dart';
import '../../model/topic_model.dart';
import '../../routes/whl_app_pages.dart';
import '../../widgets/brick/brick.dart';
import '../whl_home/whl_publish/whl_publish_logic.dart';
import 'square_logic.dart';

class SquarePage extends StatelessWidget {
  SquarePage({Key? key}) : super(key: key);

  final logic = Get.put(SquareLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: kAppColor('#F9F9F9'),
      body: Stack(
        children: [
          UIContainer(
              width: double.maxFinite,
              height: double.maxFinite,
              gradientStartColor: kAppColor('#FFFFFF'),
              gradientEndColor: kAppColor('#F3F3F3'),
              gradientBegin: Alignment.topCenter,
              gradientEnd: Alignment.bottomCenter),
          UIColumn(
            margin: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                alignment: Alignment.centerLeft,
                width: 250.w,
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                child: TabBar(
                  controller: logic.tabController,
                  labelColor: kAppTextColor,
                  labelStyle: TextStyle(
                      fontSize: 20.sp,
                      color: kAppColor('#151718'),
                      fontWeight: FontWeight.bold),
                  unselectedLabelStyle: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.white.withOpacity(0.7),
                  ),
                  indicatorColor: kAppTextColor,
                  indicatorSize: TabBarIndicatorSize.label,
                  indicatorWeight: 3,
                  // labelPadding: EdgeInsets.zero,
                  indicatorPadding: EdgeInsets.symmetric(horizontal: 10.w),
                  isScrollable: true,
                  onTap: (int index) {
                    if (index == 1) {
                      MyToast.show('该功能暂未开放');
                      logic.tabController.animateTo(0);
                    }
                  },
                  unselectedLabelColor: kAppColor('#9C9C9C'),
                  tabs: logic.naviList.map((e) {
                    return Tab(text: e.title);
                  }).toList(),
                ),
              ),
              Expanded(
                child: ExtendedTabBarView(
                  // shouldIgnorePointerWhenScrolling: false,
                  controller: logic.tabController,
                  children: [
                    buildSquareView(),
                    // UIEmptyWidget(),
                    MyEmptyWidget(
                      title: '该功能暂未开放',
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      floatingActionButton: UIRow(
        mainAxisAlignment: MainAxisAlignment.end,
        margin: EdgeInsets.only(bottom: 15.w),
        children: [
          UIRow(
            padding:
                EdgeInsets.only(left: 8.w, right: 18.w, top: 7.w, bottom: 7.w),
            color: kAppColor('#FFE800'),
            radius: 100.w,
            children: [
              UIImage(
                assetImage: 'icon_square_send.png',
                width: 28.w,
                height: 28.w,
              ),
              UIText(
                text: '发布动态',
                textColor: kAppTextColor,
                fontSize: 13.sp,
                fontWeight: FontWeight.bold,
                onTap: () {
                  logic.toSendPage();
                },
              )
            ],
          ),
        ],
      ),
    );
  }

  Widget buildSquareView() {
    return GetBuilder<SquareLogic>(builder: (logic) {
      return Column(
        children: [
          Container(
            width: ScreenUtil().screenWidth,
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: TabBar(
              labelColor: kAppTextColor,
              labelStyle: TextStyle(
                  fontSize: 15.sp,
                  color: kAppColor('#151718'),
                  fontWeight: FontWeight.bold),
              unselectedLabelStyle: TextStyle(
                  fontSize: 15.sp, color: Colors.white.withOpacity(0.7)),
              indicatorColor: Colors.transparent,
              indicatorSize: TabBarIndicatorSize.label,
              labelPadding: EdgeInsets.symmetric(horizontal: 10.w),
              indicatorWeight: 3,
              isScrollable: true,
              unselectedLabelColor: kAppColor('#9C9C9C'),
              tabs: logic.tabList.map((e) {
                return Tab(text: e.title);
              }).toList(),
              controller: logic.subTabController,
            ),
          ),
          Expanded(
              child: ExtendedTabBarView(
            shouldIgnorePointerWhenScrolling: false,
            link: true,
            cacheExtent: 0,
            controller: logic.subTabController,
            children: logic.tabList.map((e) {
              return buildSubPageView(e);
            }).toList(),
          )),
        ],
      );
    });
  }

  Widget buildSubPageView(BaseModel tabModel) {
    // BaseModel tabModel = logic.tabList[logic.selectedTabIndex];
    return UIColumn(
      children: [
        if (tabModel.id == '4' && logic.topicList.isNotEmpty) buildTagWidget(),
        Expanded(
          child: MyRefresh(
            controller: tabModel.refreshController!,
            childBuilder: (context, physics) {
              if (tabModel.id == '3' && logic.adCode?.isEmpty == true) {
                return UIContainer(
                  color: Colors.white,
                  child: MyEmptyWidget(
                    title: '没有获取到定位，请开启定位后',
                    bottomButton: UISolidButton(
                      width: 120.w,
                      height: 34.h,
                      text: '刷新',
                      onTap: () {
                        logic.flutterLocation.startLocation();
                      },
                    ),
                  ),
                );
              }
              if ((tabModel.data ?? []).isEmpty) {
                return ListView();
              }
              return CustomScrollView(
                physics: physics,
                slivers: [
                  SliverPadding(
                    padding: EdgeInsets.zero, //(left: 12.w, right: 10.w),
                    sliver: SliverList(
                      delegate: SliverChildBuilderDelegate(
                        (context, index) {
                          DynamicModel model = tabModel.data![index];
                          return commonSquareView(
                            model: model,
                            source: DynamicDataSource.Square,
                            borderRadius: BorderRadius.zero,
                            logic: logic,
                            callBack: (type) {
                              if (type == 2) {
                                logic.loadSquareData(tabModel, isRefresh: true);
                              } else if (type == 3) {
                                logic.toEditSquarePage(model);
                              } else if (type == 4) {
                                logic.listData.remove(model);
                                logic.update();
                              } else if (type == 100) {
                                logic.pushTopSetting(model);
                              }
                            },
                          );
                        },
                        childCount: tabModel.data?.length,
                      ),
                    ),
                  )
                ],
              );
            },
            onRefresh: () {
              logic.loadSquareData(tabModel, isRefresh: true);
              if (logic.selectedSubTab.id == '4') {
                logic.loadTopicData();
              }
            },
            onLoad: () {
              logic.loadSquareData(tabModel);
            },
          ),
        )
      ],
    );
  }

  // buildTopNaviView() {
  //   return UIRow(
  //     margin: EdgeInsets.only(left: 18.w, top: 11.h, bottom: 10.w),
  //     children: [
  //       UIRow(
  //         children: logic.tabList.map((e) {
  //           int index = logic.tabList.indexOf(e);
  //           return GetBuilder<SquareLogic>(builder: (logic) {
  //             return UIText(
  //               margin: EdgeInsets.only(right: 21.w),
  //               text: e.title,
  //               textColor: logic.selectedTabIndex == index
  //                   ? kAppTextColor
  //                   : kAppColor('#9C9C9C'),
  //               fontSize: logic.selectedTabIndex == index ? 15.sp : 15.sp,
  //               fontWeight: logic.selectedTabIndex == index
  //                   ? FontWeight.bold
  //                   : FontWeight.normal,
  //               onTap: () {
  //                 logic.selectTypeChang(index);
  //               },
  //             );
  //           });
  //         }).toList(),
  //       ),
  //       Expanded(child: Container()),
  //       // UIImage(
  //       //   margin: EdgeInsets.only(left: 8.w, right: 13.w),
  //       //   assetImage: 'icon_square_notice.png',
  //       //   width: 38.w,
  //       //   decoration: BoxDecoration(boxShadow: [
  //       //     BoxShadow(
  //       //       color: Colors.black.withOpacity(0.07),
  //       //       offset: const Offset(0, 8),
  //       //       blurRadius: 30,
  //       //     )
  //       //   ]),
  //       //   onTap: () {
  //       //     Get.toNamed(Routes.screen);
  //       //   },
  //       // ),
  //     ],
  //   );
  // }

  buildTagWidget() {
    return UIColumn(
      children: [
        UIContainer(
          height: 92.w,
          child: CustomScrollView(
            physics: const ClampingScrollPhysics(),
            scrollDirection: Axis.horizontal,
            slivers: [
              SliverToBoxAdapter(
                child: UIColumn(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    tagGridView(logic.oneTopicList),
                    tagGridView(logic.twoTopicList,
                        margin: EdgeInsets.only(
                            left: 10.w, top: 5.w, bottom: 11.w)),
                  ],
                ),
              )
            ],
          ),
        ),
        UIRow(
          margin: EdgeInsets.only(bottom: 13.h, top: 10.h),
          children: [
            Expanded(
                child: UIText(
              margin: EdgeInsets.only(left: 13.w),
              text: "相关话题",
              fontSize: 15.sp,
              textColor: kAppSubTextColor,
              fontWeight: FontWeight.bold,
            )),
            UIText(
              margin: EdgeInsets.symmetric(horizontal: 10.w),
              text: "查看全部 >",
              fontSize: 11.sp,
              textColor: kAppSubTextColor,
            )
          ],
        )
      ],
    );
  }

  Widget tagGridView(List data, {EdgeInsetsGeometry? margin}) {
    return UIContainer(
        height: 38.w,
        margin: margin,
        child: ListView.builder(
          shrinkWrap: true,
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            TopicModel model = data[index];
            return UIRow(
              // width: 154.w,
              mainAxisSize: MainAxisSize.min,
              margin: EdgeInsets.only(left: 12.w),
              padding: EdgeInsets.symmetric(horizontal: 12.w),
              height: 38.w,
              radius: 19.w,
              gradientStartColor: kAppColor("#F0F0F0"),
              gradientEndColor: kAppColor("#FAFAFA"),
              gradientBegin: Alignment.topCenter,
              gradientEnd: Alignment.bottomCenter,
              strokeColor: logic.selectTopicModel == model
                  ? kAppSubTextColor
                  : Colors.transparent,
              strokeWidth: 1.w,
              children: [
                UIImage(
                  margin: EdgeInsets.only(right: 5.w),
                  assetImage: "square_tag",
                  width: 19.w,
                  height: 19.w,
                ),
                Container(
                  constraints: BoxConstraints(maxWidth: 104.w),
                  child: Text(
                    model.talkName ?? "",
                    style: TextStyle(color: kAppSubTextColor, fontSize: 12.sp),
                    overflow: TextOverflow.ellipsis,
                  ),
                )
              ],
              onTap: () {
                logic.topicItemAction(model);
              },
            );
          },
          itemCount: data.length,
        ));

    return UIContainer(
      height: 38.w,
      margin: margin,
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 10.w,
          mainAxisExtent: 154.w,
        ),
        itemBuilder: (context, index) {
          return UIText(
            // width: 154.w,
            height: 38.w,
            radius: 14.w,
            gradientStartColor: kAppColor("#F0F0F0"),
            gradientEndColor: kAppColor("#FAFAFA"),
            gradientBegin: Alignment.topCenter,
            gradientEnd: Alignment.bottomCenter,
            color: kAppWhiteColor,
            text: "文艺复兴",
            alignment: Alignment.center,
            textColor: kAppSubTextColor,
            overflow: TextOverflow.ellipsis,
            fontSize: 11.sp,
            startDrawable: UIImage(
              assetImage: "square_tag",
              width: 19.w,
              height: 19.w,
            ),
            onTap: () {},
          );
        },
        itemCount: 20,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}
